/*!
 * JavaScript Library
 * update 2017.6.14 by TernWii
 *
 */
var accessid = '';
var accesskey = '';
var host = '';
var policyBase64 = '';
var signature = '';
var callbackbody = '';
var filename = '';
var dir = '';
var key = '';
var expire = 0;
var g_object_name = '';
var now = timestamp = Date.parse(new Date()) / 1000;
var currentId='',progressId='';
var uploaders=new Array();
window.onbeforeunload = function(e) {
  e = e || window.event;
  var msg = "您确定要离开此页面吗？";

  // IE
  e.cancelBubble = true;
  e.returnValue = msg;

  // Firefox
  if(e.stopPropagation) {
    e.stopPropagation();
    e.preventDefault();
  }

  // Chrome / Safari
  return msg;
};
Date.prototype.format = function(format){
  var o = {
    "M+" : this.getMonth()+1, //month
    "d+" : this.getDate(), //day
    "h+" : this.getHours(), //hour
    "m+" : this.getMinutes(), //minute
    "s+" : this.getSeconds(), //second
    "q+" : Math.floor((this.getMonth()+3)/3), //quarter
    "S" : this.getMilliseconds() //millisecond
  }

  if(/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  }

  for(var k in o) {
    if(new RegExp("("+ k +")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
    }
  }
  return format;
}
function send_request(dir)
{
  var xmlhttp = null;
  if (window.XMLHttpRequest)
  {
    xmlhttp=new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
      $(".coverup").css('display','none');
  }
  if (xmlhttp!=null)
  {
    var serverUrl =_serverUrl+'?dir=' + dir;
    xmlhttp.open( "GET", serverUrl, false );
    xmlhttp.send( null );
    return xmlhttp.responseText
  }
  else
  {
    alert("Your browser does not support XMLHTTP.");
  }
};
function get_signature(dir)
{
  now = timestamp = Date.parse(new Date()) / 1000;
  if (expire < now + 3)
  {
    body = send_request(dir)
    var obj = eval ("(" + body + ")");
    host = obj['host']
    policyBase64 = obj['policy']
    accessid = obj['accessid']
    signature = obj['signature']
    expire = parseInt(obj['expire'])
    callbackbody = obj['callback']
    key = obj['dir']
    return true;
  }
  return false;
};

function random_string(len) {
  len = len || 32;
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  var maxPos = chars.length;
  var pwd = '';
  for (i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

function get_suffix(filename) {
  pos = filename.lastIndexOf('.')
  suffix = ''
  if (pos != -1) {
    suffix = filename.substring(pos)
  }
  return suffix;
}

function calculate_object_name(filename)
{
  var now = new Date();
  var nowStr = now.format("yyyyMMddhhmmss");
  suffix = get_suffix(filename)
  g_object_name = key + nowStr + random_string(10) + suffix
  return ''
}

function get_uploaded_object_name(filename)
{
  return g_object_name
}

function set_upload_param(up, filename, ret)
{
  //dir = document.getElementById('dir').value;
  if (ret == false)
  {
    ret = get_signature(dir)
  }
  g_object_name = key;
  if (filename != '') {
    suffix = get_suffix(filename)
    calculate_object_name(filename)
  }
  new_multipart_params = {
    'key' : g_object_name,
    'policy': policyBase64,
    'OSSAccessKeyId': accessid,
    //让服务端返回200,不然，默认会返回204
    'success_action_status' : '200',
    'callback' : callbackbody,
    'signature': signature,
  };
  up.setOption({
    'url': host,
    'multipart_params': new_multipart_params
  });
  //选择文件完毕，去除遮罩层
  $(".coverup").css('display','none');
  up.start();
}
//config options param
var _serverUrl='http://192.168.59.2:7090';
var _containerId;
var _beginId;
var _progress;
var _progressBar;
var _mime_types;
var _max_file_size;
var _prevent_duplicates;
var _onStartHandle,_uploadSucHandle,_uploadErroHandler;
var _lookHandler,_moveHandler;
var _deleHandler=null;
var cur_id='';

/*清除*/
/*读取上传配置*/
function upConfigs(_opt){
  if(_opt){
    if(_opt.serverUrl)_serverUrl=_opt.serverUrl;
    if(_opt.ossDir)dir=_opt.ossDir;
    if(_opt.containerId)_containerId=_opt.containerId;
    if(_opt.beginId)_beginId=_opt.beginId;
    if(_opt.progressStyles&&_opt.progressStyles.progress)
      _progress=_opt.progressStyles.progress;
    if(_opt.progressStyles&&_opt.progressStyles.progress_bar)
      _progressBar=_opt.progressStyles.progress_bar;
    if(_opt.mime_types)_mime_types=_opt.mime_types;
    if(_opt.max_file_size)_max_file_size=_opt.max_file_size;
    if(_opt.prevent_duplicates)_prevent_duplicates=_opt.prevent_duplicates;
    if(_opt.onStartHandle)_onStartHandle=_opt.onStartHandle;
    if(_opt.onSucHandle)_uploadSucHandle=_opt.onSucHandle;
    if(_opt.onErroHandler)_uploadErroHandler=_opt.onErroHandler;
    if(_opt.lookHandler)_lookHandler=_opt.lookHandler;
    if(_opt.moveHandler)_moveHandler=_opt.moveHandler;
    if(_opt.deleHandler)_deleHandler=_opt.deleHandler;
  }
}
/*
 *左右移动上传控件
 *内部调用
 */
function moveItem(direct,_target){
  var _id=$(_target).attr('id').replace('mv_','');
  var $current=$("#b"+_id);
  var $container=$current.parent();
  var len=$container.find('.active').length;
  if(len<2)return;
  var $list=[];
  var i=0,j=0,$item;
  $container.find('.active').each(function(){
    if('b'+_id==$(this).attr('id')){
      $item=$(this);
      j=i;
    }
    $list.push($(this));
    i++;
  });
  if(direct==-1){
    //左移
    if(j!=0)
      $list[j-1].remove().insertAfter($item);
    else{
      $item.remove().insertAfter($list[len-1]);
    }
  }
  else if(direct==1){
    if(j!=len-1)
      $list[j+1].remove().insertBefore($item);
    else
      $item.remove().insertBefore($list[0]);
  }
  var event = event || window.event;  //用于IE
  if(event.preventDefault) event.preventDefault();  //标准技术
  if(event.returnValue) event.returnValue = false;  //IE
  return false;
}
/*
 *以藏一个不需要的上传控件
 *内部调用
 */
function deleItem(_target){
  var _id=$(_target).attr('id').replace('d_','');
  if(_deleHandler){
    _deleHandler(_id);
    return;
  }
  deleUploaderById(_id);
  var event = event || window.event;  //用于IE
  if(event.preventDefault) event.preventDefault();  //标准技术
  if(event.returnValue) event.returnValue = false;  //IE
  return false;
}
/*
 *销毁不再需要的上传控件
 *可外部调用
 */
function deleUploaderById(_id){
  if(uploaders[_id])uploaders[_id].destroy();
  $("#b"+_id).html('');
  $("#b"+_id).remove();
}
/*
 *放大查看图片
 *外部详细定义
 */
function expItem(_target){
  var _id=$(_target).attr('id').replace('exp_','');
  if(_lookHandler)_lookHandler($('#img_'+_id).attr('src'));
  var event = event || window.event;  //用于IE
  if(event.preventDefault) event.preventDefault();  //标准技术
  if(event.returnValue) event.returnValue = false;  //IE
  return false;
}
/*
 *加载上次的上传结果，参数为一字符串数组，可能加载页面时从后台获得
 */
function setLastPath(_path,$_box){
  var idx=new Date().getTime();
  var $box=$_box;
  if(!$box)$box=$("#"+_containerId);
  newUploadView(idx,$box,_path);
  createLoader(idx);
}

/*
 *新增图片上传控件
 *pram _id 上传控件页面id,唯一性
 */
function addUploaderView(_id,_path){
  var img=_path;
  if(img==undefined||img==null)img='';
  newUploadView(_id,$("#"+_containerId),img);
  createLoader(_id);

}
function addUploaderViewAt(_id,$_box){
  newUploadView(_id,$_box,'');
  createLoader(_id);
}
//新建uploader
function newUploadView(_id,$_box,_path){
  $_box.append("<div id='b"+_id+"' class='upitem active'><div class='upbtn'><i id='mv_"
    +_id+"' onclick='moveItem(-1,this)' class='icon icon-arrow-left'></i>&nbsp;&nbsp;&nbsp;<i id='mv_"
    +_id+"' class='icon icon-arrow-right' onclick='moveItem(1,this)'></i>&nbsp;&nbsp;&nbsp;<i id='exp_"
    +_id+"' class='icon icon-expand-full' onclick='expItem(this)'></i>&nbsp;&nbsp;&nbsp;&nbsp;<i id='d_"
    +_id+"'  class='icon icon-remove-sign' onclick='deleItem(this)'></i></div><div id='ossfile"
    +_id+"' class='ossprog' onclick='upClick(this)'></div><div class='ossprog coverup' id='cover_"
    +_id+"' style='background-color:#ccc;z-index:1002;display:none;opacity:.5;'></div><img id='img_"
    +_id+"' src='"+_path+"'/></div>");
	if(typeof(_uploadSucHandle)=="function"&&_path){
	  $("#ossfile"+_id).html('');
	  _uploadSucHandle(_path,_id);
	}
}
//创建上传file input
function createLoader(subid){
  var uploader = new plupload.Uploader({
    runtimes : 'html5,flash,silverlight,html4',
    browse_button :document.getElementById("ossfile"+subid),
    multi_selection: true,
    container:document.getElementById('b'+subid),
    flash_swf_url : '../../../lib/js/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url : '../../../lib/js/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
    filters: {
      mime_types :_mime_types,
      max_file_size :_max_file_size,
      prevent_duplicates :_prevent_duplicates
    },

    init :
      {
        PostInit : function() {
          document.getElementById("ossfile"+subid).innerHTML = '';
          if(false){
            //改自动，废弃开始上传按钮
            //document.getElementById(_beginId).onclick = function() {
            //set_upload_param(uploader, '', false);
            //if(_onStartHandle)_onStartHandle();
            //return false;
            //};
          }
        },

        FilesAdded : function(up, files) {
          plupload.each(
            files,
            function(file) {
              document.getElementById("ossfile"+subid).innerHTML = '<div id="'
                + file.id
                + '">'
                + ''//file.name
                + ' ('
                + plupload
                  .formatSize(file.size)
                + ')<span></span>'
                + '<div class="'+_progress+'"><div class="'+_progressBar+'" style="width: 0%"></div></div>'
                + '</div>';
            });
          //自动上传
          set_upload_param(uploader, '', false);
          if(_onStartHandle)_onStartHandle();
        },

        BeforeUpload : function(up, file) {
          set_upload_param(up, file.name, true);
        },

        UploadProgress : function(up, file) {
          var d = document.getElementById(file.id);
          if(d==null)return;
          d.getElementsByTagName('span')[0].innerHTML = '<span>'
            + file.percent + "%</span>";
          var prog = d.getElementsByTagName('div')[0];
          var progBar = prog.getElementsByTagName('div')[0]
          progBar.style.width = 2 * file.percent + 'px';
          progBar.setAttribute('aria-valuenow', file.percent);
        },

        FileUploaded : function(up, file, info) {
          if (info.status == 200) {
            if(typeof(_uploadSucHandle)=="function"){
              $("#img_"+cur_id).attr('src',host + "/" + get_uploaded_object_name(file.name));
              $("#ossfile"+cur_id).html('');
              _uploadSucHandle(host + "/" + get_uploaded_object_name(file.name),cur_id);
            }

          } else {
            console.log('one failed');
          }
        },

        Error : function(up, err) {
          var errMsg='';
          if (err.code == -600)
            errMsg="选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小";
          else if (err.code == -601)
            errMsg="选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型";
          else if (err.code == -602)
            errMsg="这个文件已经上传过一遍了";
          else
            errMsg=err.response;
          $("#ossfile"+cur_id).html('');
          if(typeof(_uploadErroHandler)=="function"){
            _uploadErroHandler(err.code,errMsg);
          }
        }
      }
  });
  uploader.init();
  uploaders[subid]=uploader;

}
var timer=null;
function upClick(_target){
  cur_id=$(_target).attr('id').replace('ossfile','');
  $(".coverup").css('display','block');
  timer=setTimeout("hideCover()",1000);
}
function hideCover (){
  timer=null;
  $(".coverup").css('display','none');
}
/*
 *获取全部上传结果，返回一组oss图片地址
 */
function getUploads($_container){
  var paths=[];
  var $container=$_container;
  if(!$container)$container=$("#"+_containerId);
  $container.find(".upitem").each(function(){
    if($(this).attr('class').indexOf('dele')==-1)
      paths.push($(this).find('img').attr('src'));
  });
  return paths;
}